package com.chensi.admin.userservice.controller;

import com.chensi.admin.userservice.dto.CmsActivityDTO;
import com.chensi.admin.userservice.common.BaseErrorCode;
import com.chensi.admin.userservice.common.Constants;
import com.chensi.admin.userservice.common.JsonResult;
import com.chensi.admin.userservice.exception.BaseException;
import com.chensi.admin.userservice.feign.CmsService;
import com.chensi.admin.userservice.domain.CmsActivityApply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * @author si.chen
 * @date 2019/6/24 15:09
 */

@RestController
@RequestMapping("/user/cms")
public class UserCmsController {

    private final CmsService cmsService;

    @Autowired
    public UserCmsController(CmsService cmsService) {
        this.cmsService = cmsService;
    }

    /**
     * 用户服务-获取CMS所有活动
     *
     * @return 活动集合
     */
    @GetMapping("/activity")
    public ResponseEntity<JsonResult> list() {
        ResponseEntity<JsonResult<List<CmsActivityDTO>>> list = cmsService.list();
        int httpCode = list.getStatusCodeValue();
        String code = Objects.requireNonNull(list.getBody()).getCode();
        if (httpCode == Constants.HTTP_CODE && code.equals(Constants.CODE)) {
            return ResponseEntity.ok(
                    JsonResult.ok(list)
            );
        } else {
            return ResponseEntity.ok(
                    JsonResult.failed(BaseErrorCode.UNKNOWN_EXCEPTION)
            );
        }

    }

    /**
     * 用户服务-用户报名活动
     *
     * @param cmsActivityApply 活动id，报名人员id
     * @return 报名状态
     * @throws BaseException 报名异常
     */
    @PostMapping("/apply")
    public ResponseEntity<JsonResult> save(@Valid @RequestBody CmsActivityApply cmsActivityApply) throws BaseException {
        ResponseEntity<JsonResult> jsonResult = cmsService.save(cmsActivityApply);
        int httpCode = jsonResult.getStatusCodeValue();
        String code = Objects.requireNonNull(jsonResult.getBody()).getCode();
        if (httpCode == Constants.HTTP_CODE && code.equals(Constants.CODE)) {
            return ResponseEntity.ok(
                    JsonResult.ok()
            );
        } else {
            return ResponseEntity.ok(
                    JsonResult.failed(BaseErrorCode.UNKNOWN_EXCEPTION)
            );
        }

    }


}
